//
//  MMMemePickerViewController.m
//  MemeMaker
//
//  Created by Phan Quang Ha on 7/22/13.
//  Copyright (c) 2013 soyo. All rights reserved.
//

#import "MMMemePickerViewController.h"
#import "MMConstants.h"
#import "UITableViewCell+LoadFromNib.h"
#import "MMCameraAndImagePickerViewController.h"

#import "MMImageView.h"
#import "UIBarButtonItem+Custom.h"

@interface MMMemePickerViewController ()
{
    NSMutableArray *arrSources;
    NSInteger numberOfRows;
}
@property (strong, nonatomic) IBOutlet UISegmentedControl *segmentImages;
- (IBAction)changeSources:(UISegmentedControl *)sender;
@end

@implementation MMMemePickerViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        arrSources = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [self.btnGallery setTitle:NSLocalizedString(@"capture", @"")];
//    [self.toolbar setTintColor:TOOLBAR_TINT_COLOR];
    GADBannerView *adBanner = [[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner];
    adBanner.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    adBanner.rootViewController = self;
    adBanner.adUnitID = ADMOB_PUBLISHER_ID;
    adBanner.delegate = self;
    [self.viewAd addSubview:adBanner];
    [adBanner loadRequest:[GADRequest request]];
    
//    [self tapMemeSource:nil];
    [self getContentsOfFolder:FOLDER_MEME];
    [self generateTopAction];
    
    
}

- (void) generateTopAction
{
    UIBarButtonItem *btnBack = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(back:)];
    [self.navigationItem setLeftBarButtonItem:btnBack];
    
    [self.segmentImages removeFromSuperview];
    UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:self.segmentImages];
    [self.navigationItem setRightBarButtonItem:barBtn];
    
//    UIBarButtonItem *btnRef = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(tapMemeSource:)];
//    UIBarButtonItem *btnCapture = [UIBarButtonItem barItemWithImage:[UIImage imageNamed:@"ico_camera.png"] size:CGSizeMake(35, 35) target:self action:@selector(tabGallerySource:)];
//    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:btnCapture, btnRef, nil]];
    
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    if ([kMMManagerData isBackFromCamara] == YES) {
//        [kMMManagerData setIsBackFromCamara:NO];
//        [self.navigationController popViewControllerAnimated:YES];
//    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setTblGallery:nil];
    [super viewDidUnload];
}


- (void)back:(id)sender {
    if (_delegate && [_delegate respondsToSelector:@selector(didSelectImage:)]) {
        [_delegate didSelectImage:nil];
    }
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)tapVoiceBoxSource:(UIButton *)sender {
    sender.selected = YES;
    [self getContentsOfFolder:FOLDER_VOICE_BOX];
    [self.tblGallery reloadData];
    
}
- (void)tapMemeSource:(id)sender {
    [self getContentsOfFolder:FOLDER_MEME];
    [self.tblGallery reloadData];
}


- (void)tabGallerySource:(id)sender {
    MMCameraAndImagePickerViewController *cameraVC = [[MMCameraAndImagePickerViewController alloc] initWithNibName:@"MMCameraAndImagePickerViewController" bundle:nil];
    cameraVC.delegate = self;
    [cameraVC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:cameraVC animated:YES];
}


- (void) getContentsOfFolder:(NSString *)folder
{
    [arrSources removeAllObjects];
    
    NSString *folderPath = [NSString stringWithFormat:@"%@/%@", DOCUMENT_FOLDER, folder];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *filesPath = [fileManager contentsOfDirectoryAtPath:folderPath error:nil];
    NSInteger cellCount = 0;
    if (filesPath.count > 0) {
        if (filesPath.count % 3 == 0) {
            cellCount = filesPath.count/3;
        }else{
            cellCount = filesPath.count/3 + 1;
        }
    }
    
    for (int i = 0; i<cellCount; i++) {
        NSMutableArray *oneCellImages = [NSMutableArray arrayWithCapacity:3];
        for (int j = 0; j<3; j++) {
            if (i*3+j < filesPath.count) {
                NSInteger cIndex = i*3 + j;
                [oneCellImages addObject:[folderPath stringByAppendingPathComponent:[filesPath objectAtIndex:cIndex]]];
            }
        }
        [arrSources addObject:oneCellImages];
    }
}
#pragma mark - UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"arr source count: %i", [arrSources count]);
    if ([arrSources count] > 0) {
        return [arrSources count];
    }
    return 1;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MMImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:idImagesCell];
    if (!cell) {
        cell = [UITableViewCell loadCellFromNibName:@"MMImagesCell"];
        cell.delegate = self;
        cell.imgView1.isHiddenName = YES;
        cell.imgView2.isHiddenName = YES;
        cell.imgView3.isHiddenName = YES;
    }
    NSArray *arr = [arrSources objectAtIndex:indexPath.row];
    [cell setImagesWithPaths:arr];
    return cell;
}

#pragma mark - MMImagesCellDelegate
- (void)didTouchImage:(UIImage *)img withName:(NSString *)name
{
    if (img) {
        
//        NSData *imgData = UIImageJPEGRepresentation(img, 1.0);
//        UIImage *newImg = [UIImage imageWithData:imgData];
        if (_delegate && [_delegate respondsToSelector:@selector(didSelectImage:)]) {
            [_delegate didSelectImage:img];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}


#pragma mark - MMCamera delegate
- (void) didReceivedImage:(UIImage *)img {
    if (_delegate && [_delegate respondsToSelector:@selector(didSelectImage:)]) {
        [_delegate didSelectImage:img];
    }
}
#pragma mark - ADBanner
- (void)adViewDidReceiveAd:(GADBannerView *)view
{
    [UIView animateWithDuration:0.2 animations:^{
        CGRect tableRect = self.tblGallery.frame;
        CGRect bannerRect = self.viewAd.frame;
        
        tableRect.size.height = self.view.frame.size.height - bannerRect.size.height;
        bannerRect.origin.y = tableRect.size.height;
        
        self.tblGallery.frame = tableRect;
        self.viewAd.frame = bannerRect;
    }];
}
- (void)adView:(GADBannerView *)view didFailToReceiveAdWithError:(GADRequestError *)error
{
    NSLog(@"Ad Error:%@",error);
    [UIView animateWithDuration:0.2 animations:^{
        CGRect tableRect = self.tblGallery.frame;
        CGRect bannerRect = self.viewAd.frame;
        
        tableRect.size.height = self.view.frame.size.height;
        bannerRect.origin.y = tableRect.size.height;
        
        self.tblGallery.frame = tableRect;
        self.viewAd.frame = bannerRect;
    }];
}

- (IBAction)changeSources:(UISegmentedControl *)sender {
    if (sender.selectedSegmentIndex == 0) {
        [self getContentsOfFolder:FOLDER_MEME];
        [self.tblGallery reloadData];
    }else{
        [self getContentsOfFolder:FOLDER_MEME2];
        [self.tblGallery reloadData];
    }
}
@end
